package com.peng.herostory;

import com.peng.herostory.cmdhanlder.CmdHandlerFactory;
import com.peng.herostory.mq.MqProducer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class GameMain {
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        CmdHandlerFactory.init();
        GameMsgRecognizer.init();
        MySqlSessionFactory.init();
        MqProducer.init();
        try {
            ChannelFuture future = bootstrap
                    .group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline()
                                    .addLast(new HttpServerCodec())
                                    .addLast(new HttpObjectAggregator(65535))
                                    .addLast(new WebSocketServerProtocolHandler("/websocket"))
                                    .addLast(new GameMsgEncoder())
                                    .addLast(new GameMsgDecoder())
                                    .addLast(new GameChannelHandler());
                        }
                    })
                    .bind(8888)
                    .sync();
            if (!future.isSuccess()) {
                log.error("服务器启动失败。。");
                return;
            }
            log.info("服务器启动成功。。");
            future.channel().closeFuture().sync();

        } catch (Exception e) {
            log.error("e:{}", e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }
}
